﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using BLL;
using Model;
using WebApplication1.App_Code;
using System.Web.UI;
using System.IO;
using Wuqi.Webdiyer;
using System.Data;

namespace WebApplication1.RecordView
{
    public partial class ToolRecordView : System.Web.UI.Page
    {
        private string var_ToolType { get { return ViewState["ToolType"].ToString(); } set { ViewState["ToolType"] = value; } }
        private string var_WorkShop { get { return ViewState["WorkShop"].ToString(); } set { ViewState["WorkShop"] = value; } }
        private string var_DistributionArea { get { return ViewState["DistributionArea"].ToString(); } set { ViewState["DistributionArea"] = value; } }
        private string var_ToolState { get { return ViewState["ToolState"].ToString(); } set { ViewState["ToolState"] = value; } }
        private string var_RepairRecord { get { return ViewState["RepairRecord"].ToString(); } set { ViewState["RepairRecord"] = value; } }
        private string var_ToolName { get { return ViewState["ToolName"].ToString(); } set { ViewState["ToolName"] = value; } }
        private string var_ToolCode { get { return ViewState["ToolCode"].ToString(); } set { ViewState["ToolCode"] = value; } }
        private string var_ToolEnableSN { get { return ViewState["ToolEnableSN"].ToString(); } set { ViewState["ToolEnableSN"] = value; } }
        private string var_Taker { get { return ViewState["Taker"].ToString(); } set { ViewState["Taker"] = value; } }
        private string var_TakerID { get { return ViewState["TakerID"].ToString(); } set { ViewState["TakerID"] = value; } }
        private string var_ProductType { get { return ViewState["ProductType"].ToString(); } set { ViewState["ProductType"] = value; } }
        private string var_ProductTypeID { get { return ViewState["ProductTypeID"].ToString(); } set { ViewState["ProductTypeID"] = value; } }
        private ToolRecord tr;
        private Config c;

        public ToolRecordView()
        {
            tr = new ToolRecord();
            c = new Config();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDropDownList(this.DDL_ToolType, enum_configType.TOOL_TYPE);
                BindDropDownList(this.DDL_WorkShop, enum_configType.WORK_SHOP);
                BindDropDownList(this.DDL_DistrbutionArea, enum_configType.DISTRIBUTION_AREA);
                BindDropDownList(this.DDL_ToolState, enum_configType.TOOL_STATE);
                BindDropDownList(this.DDL_RepairRecord, enum_configType.REPAIR_RECORD);
            }
        }

        public void BindDropDownList(DropDownList ddl, enum_configType ct)
        {
            ddl.DataSource = c.Config_GetAll_forSingleType(ct);
            ddl.DataTextField = "ItemName";
            ddl.DataValueField = "ItemName";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("请选择", ""));
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var_ToolType = this.DDL_ToolType.SelectedItem.Text;
            var_WorkShop = this.DDL_WorkShop.SelectedItem.Text;
            var_DistributionArea = this.DDL_DistrbutionArea.SelectedItem.Text;
            var_ToolState = this.DDL_ToolState.SelectedItem.Text;
            var_RepairRecord = this.DDL_RepairRecord.SelectedItem.Text;
            var_ToolName = this.Tb_ToolName.Text.Trim();
            var_ToolCode = this.Tb_ToolCode.Text.Trim();
            var_ToolEnableSN = this.Tb_EnableSN.Text.Trim();
            var_Taker = this.Tb_Taker.Text.Trim();
            var_TakerID = this.Tb_TakerID.Text.Trim();
            var_ProductType = this.Tb_ProductType.Text.Trim();
            var_ProductTypeID = this.Tb_ProductTypeName.Text.Trim();
            BindToolRecordStatistics(); 
            if(this.ButImport.Visible==false)
            {
                this.ButImport.Visible = true; 
            }
        }

        public void BindToolRecordStatistics()
        {
            ToolRecordInfo tri = new ToolRecordInfo
            {
                ID = 0,
                Record_Mode = "",
                Record_Date = DateTime.Now,
                Work_Shop = var_WorkShop.Equals("请选择") ? null : var_WorkShop,
                Tool_Type = var_ToolType.Equals("请选择") ? null : var_ToolType,
                ProductType = string.IsNullOrEmpty(var_ProductType) ? null : var_ProductType,
                ProductTypeName = string.IsNullOrEmpty(var_ProductTypeID) ? null : var_ProductTypeID,
                Tool_Code = string.IsNullOrEmpty(var_ToolCode) ? null : var_ToolCode,
                Tool_Name = string.IsNullOrEmpty(var_ToolName) ? null : var_ToolName,
                Tool_Type_Spec = "",
                Tool_EnableSN = string.IsNullOrEmpty(var_ToolEnableSN) ? null : var_ToolEnableSN,
                Amount = 0,
                Taker = string.IsNullOrEmpty(var_Taker) ? null : var_Taker,
                Taker_ID = string.IsNullOrEmpty(var_TakerID) ? null : var_TakerID,
                Distribution_Area = var_DistributionArea.Equals("请选择") ? null : var_DistributionArea,
                Tool_State = var_ToolState.Equals("请选择") ? null : var_ToolState,
                Repair_Record = var_RepairRecord.Equals("请选择") ? null : var_RepairRecord,
                Remark = "" 
            };
            IList<ToolRecordInfo> list = tr.ToolRecord_StatisticsbyMultiFact(tri);
            //this.GridView1.DataSource = list;
            //this.GridView1.DataBind();
            //初始化分页数据源实例
            PagedDataSource pds = new PagedDataSource();
            //设置总行数
            AspNetPager1.RecordCount = list.Count;
            //设置分页的数据源
            pds.DataSource = list;
            //设置当前页
            pds.CurrentPageIndex = AspNetPager1.CurrentPageIndex - 1;
            //设置每页显示页数
            pds.PageSize = AspNetPager1.PageSize;
            //启用分页
            pds.AllowPaging = true;
            //设置GridView的数据源为分页数据源
            GridView1.DataSource = pds;
            //绑定GridView
            GridView1.DataBind();

            this.Lbl_RecordsCount.Text = list.Count.ToString();
            int amount = 0;//库存数
            //int amount_input = 0;//入库
            //int amount_output = 0;//出库
            //int amount_writeoff = 0;//报废
            foreach (ToolRecordInfo trinfo in list)
            {
                //if (trinfo.Distribution_Area == "工具房") //同一个启用编号
                //{
                //    if (var_ToolEnableSN == trinfo.Tool_EnableSN && var_ToolCode == trinfo.Tool_Name)
                //    {
                //        if (trinfo.Record_Mode == "入库")
                //        {
                //            amount_input += trinfo.Amount_Input; //入库 
                //        }
                //        else if (trinfo.Record_Mode == "出库")
                //        {
                //            amount_output += trinfo.Amount_Output; //出库
                //        }
                //        else
                //        {
                //            amount_writeoff += trinfo.Amount_WriteOff; //报废
                //        }

                //    }
                //}
                //else
                //{
                //    if (var_ToolEnableSN == trinfo.Tool_EnableSN && var_ToolCode == trinfo.Tool_Name)
                //    {
                //        if (trinfo.Record_Mode == "入库")
                //        {
                //            amount_input += trinfo.Amount_Input; //入库 
                //        }
                //        else if (trinfo.Record_Mode == "出库")
                //        {
                //            amount_output += trinfo.Amount_Output; //出库
                //        }
                //        else
                //        {
                //            amount_writeoff += trinfo.Amount_WriteOff; //报废
                //        }

                //    }

                //}
                amount += trinfo.Amount;
            }
            //foreach (ToolRecordInfo trinfo in list)
            //{
            //    if (trinfo.Distribution_Area != "工具房") //同一个启用编号
            //    {
            //        if (amount_output != 0 && amount_writeoff != 0)
            //        {
            //            //库存数量=出库数-报废数；
            //            amount = amount_output - amount_writeoff;
            //        }
            //        else
            //        {
            //            //库存数量=出库数
            //            amount = amount_output;
            //        }
            //    }
            //    else
            //    {
            //        if (amount_input != 0 && amount_output != 0)
            //        {
            //            //库存数量=入库数-出库数
            //            amount = amount_input - amount_output;

            //        }
            //        else
            //        {
            //            //库存数量=入库数
            //            amount = amount_input;
            //        } 
            //    }
            //}

            //this.Lbl_Amount.Text = amount.ToString();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GridView1.PageIndex = e.NewPageIndex;
            BindToolRecordStatistics();
        }


        #region 根据条件导出数据
        /// 2017/08/29 xl
          /**//// <summary>
        /// 实现对IList到DataSet的转换
        /// </summary>
        /// <param name="ResList">待转换的IList</param>
        /// <returns>转换后的DataSet</returns>
        public static DataSet ListToDataSet(IList<ToolRecordInfo> ResList)
        {
            DataSet RDS = new DataSet();
            DataTable TempDT = new DataTable();
            //此处遍历IList的结构并建立同样的DataTable
            if (ResList.Count != 0)
            {
                System.Reflection.PropertyInfo[] p = ResList[0].GetType().GetProperties();
                foreach (System.Reflection.PropertyInfo pi in p)
                {
                    TempDT.Columns.Add(pi.Name, System.Type.GetType(pi.PropertyType.ToString()));
                }
                for (int i = 0; i < ResList.Count; i++)
                {
                    IList TempList = new ArrayList();
                    //将IList中的一条记录写入ArrayList
                    foreach (System.Reflection.PropertyInfo pi in p)
                    {
                        if (pi.Name == "Amount_Input" || pi.Name == "Amount_Output" || pi.Name == "Amount_WriteOff")
                        {
                            break;
                        }
                        object oo = pi.GetValue(ResList[i], null);
                        TempList.Add(oo);
                    }

                    object[] itm = new object[p.Length];
                    //遍历ArrayList向object[]里放数据
                    for (int j = 0; j < TempList.Count; j++)
                    {
                        itm.SetValue(TempList[j], j);
                    }
                    //将object[]的内容放入DataTable
                    TempDT.LoadDataRow(itm, true);
                }
                //将DateTable放入DataSet
                RDS.Tables.Add(TempDT);
            }
            //返回DataSet
            return RDS;
        }

         /// 最终报表生成 
        /// 2017/08/29 xl
        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param> 
        public string GetPath(string var_ToolType,string var_WorkShop,string var_DistributionArea, string var_ToolState, string var_RepairRecord
                   , string var_ToolName, string var_ToolCode, string var_ToolEnableSN, string var_Taker, string var_TakerID, string var_ProductType, string var_ProductTypeID)
        {
            ToolRecordInfo tri = new ToolRecordInfo
            {
                ID = 0,
                Record_Mode = "",
                Record_Date = DateTime.Now,
                Work_Shop = var_WorkShop.Equals("请选择") ? null : var_WorkShop,
                Tool_Type = var_ToolType.Equals("请选择") ? null : var_ToolType,
                ProductType = string.IsNullOrEmpty(var_ProductType) ? null : var_ProductType,
                ProductTypeName = string.IsNullOrEmpty(var_ProductTypeID) ? null : var_ProductTypeID,
                Tool_Code = string.IsNullOrEmpty(var_ToolCode) ? null : var_ToolCode,
                Tool_Name = string.IsNullOrEmpty(var_ToolName) ? null : var_ToolName,
                Tool_Type_Spec = "",
                Tool_EnableSN = string.IsNullOrEmpty(var_ToolEnableSN) ? null : var_ToolEnableSN,
                Amount = 0,
                Taker = string.IsNullOrEmpty(var_Taker) ? null : var_Taker,
                Taker_ID = string.IsNullOrEmpty(var_TakerID) ? null : var_TakerID,
                Distribution_Area = var_DistributionArea.Equals("请选择") ? null : var_DistributionArea,
                Tool_State = var_ToolState.Equals("请选择") ? null : var_ToolState,
                Repair_Record = var_RepairRecord.Equals("请选择") ? null : var_RepairRecord,
                Remark = ""
            };
            IList<ToolRecordInfo> list = tr.ToolRecord_StatisticsbyMultiFact(tri);
            DataSet ds = ListToDataSet(list);
            DataTable dt=new DataTable();
            if(ds.Tables.Count!=0)
            {
                 dt = ds.Tables[0];
            }

            string filepath = Server.MapPath("~/") + @"\RecordView\report\";//在该项目下建的一个文件夹
            DataRow rowPart;
            System.Data.DataTable workTable = new System.Data.DataTable("LX");
            workTable.Columns.Add("车间");
            workTable.Columns.Add("类别");
            workTable.Columns.Add("应用产品");
            workTable.Columns.Add("应用产品代码");
            workTable.Columns.Add("代码");
            workTable.Columns.Add("名称");
            workTable.Columns.Add("规格型号");

            workTable.Columns.Add("启用编码");
            workTable.Columns.Add("库存数量");
            workTable.Columns.Add("分布区域");
            workTable.Columns.Add("状态");
            workTable.Columns.Add("修复记录");
            workTable.Columns.Add("备注");
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    rowPart = workTable.NewRow();
                    rowPart["车间"] = dt.Rows[i]["Work_Shop"].ToString();
                    rowPart["类别"] = dt.Rows[i]["Tool_Type"].ToString();
                    rowPart["应用产品"] = dt.Rows[i]["ProductType"].ToString();
                    rowPart["应用产品代码"] = dt.Rows[i]["ProductTypeName"].ToString();
                    rowPart["代码"] = dt.Rows[i]["Tool_Code"].ToString();
                    rowPart["名称"] = dt.Rows[i]["Tool_Name"].ToString();
                    rowPart["规格型号"] = dt.Rows[i]["Tool_Type_Spec"].ToString();
                    rowPart["启用编码"] = dt.Rows[i]["Tool_EnableSN"].ToString();
                    rowPart["库存数量"] = dt.Rows[i]["Amount"].ToString();
                    rowPart["分布区域"] = dt.Rows[i]["Distribution_Area"].ToString();
                    rowPart["状态"] = dt.Rows[i]["Tool_State"].ToString();
                    rowPart["修复记录"] = dt.Rows[i]["Repair_Record"].ToString();
                    rowPart["备注"] = dt.Rows[i]["Remark"].ToString();
                    workTable.Rows.Add(rowPart);
                }

            }

            return  ExportToTxt(workTable, filepath);
 
        }

        // 2017/08/29 xl
        private const string CSVPOSTFIX = ".xls"; 
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="table"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ExportToTxt(DataTable table, string path)
        {
            string tempFileName = null;
            tempFileName = "工装工具数据"+ GetTempFileName()  ; 
            string filepath = path + tempFileName + CSVPOSTFIX;
            string filename = tempFileName + CSVPOSTFIX;
            System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.Create);
            System.IO.StreamWriter textFile = new System.IO.StreamWriter(fs, System.Text.Encoding.Unicode);
            //把Dataset中的数据写入.xls文件中 

            //统计dataset中当前表的行数 
            int row = table.Rows.Count;

            //统计dataset中当前表的列数 
            int column = table.Columns.Count;

            //把dataset中当前表的字段名写入.xls文件中 
            for (int i = 0; i < column; i++)
            {
                if (i < column - 1)
                    textFile.Write(table.Columns[i].ColumnName.ToString().Replace("\r\n", " ").Replace("\t", " ") + "\t");
                else
                    textFile.Write(table.Columns[i].ColumnName.ToString().Replace("\r\n", " ").Replace("\t", " ") + "\n");
            }
            //把dataset中当前表的数据写入.xls文件中 
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < column; j++)
                {
                    if (j < column - 1)
                        textFile.Write(table.Rows[i][j].ToString().Replace("\r\n", " ").Replace("\t", " ") + "\t");
                    else
                        textFile.Write(table.Rows[i][j].ToString().Replace("\r\n", " ").Replace("\t", " ") + "\n");
                }
            }
            //关闭当前的StreamWriter流 
            textFile.Close();
            return filename;
        } 

        /// <summary>
        /// 生成文件名称
        /// </summary>
        /// <returns></returns>
        public static string GetTempFileName()
        {
            return DateTime.Now.ToString("yyyyMMddhhmmssfff");
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButImport_Click(object sender, EventArgs e)
        {
            string filenamePart = GetPath(var_ToolType, var_WorkShop, var_DistributionArea, var_ToolState, var_RepairRecord
               , var_ToolName, var_ToolCode, var_ToolEnableSN, var_Taker, var_TakerID, var_ProductType, var_ProductTypeID);
            string strFilePath = Server.MapPath("~") + @"\RecordView\report\" + filenamePart;//服务器文件路径

            FileInfo fileInfo = new FileInfo(strFilePath);

            Response.Clear();

            Response.Charset = "GB2312";

            Response.ContentEncoding = System.Text.Encoding.UTF8;

            Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(fileInfo.Name));

            Response.AddHeader("Content-Length", fileInfo.Length.ToString());

            Response.ContentType = "application/x-bittorrent";

            Response.WriteFile(fileInfo.FullName);

            Response.End();

        } 

        #endregion


        /// <summary>
        /// 添加分页功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            //调用绑定分页和GridView
            AspNetPager1.CurrentPageIndex = (sender as AspNetPager).CurrentPageIndex;
            BindToolRecordStatistics();
        }

   
    }
}
